import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity,
  Alert,
  TextInput,
  ScrollView,
} from "react-native";
import * as FileSystem from "expo-file-system";
import PageContainer from "@/components/PageContainer";
import React, { useState } from "react";
import useInputWithDone from "@/hooks/useInputWithDone";
import { useRouter } from "expo-router"; // 引入 useRouter
import useAppStateChange from "@/hooks/useAppStateChange";
import * as ImagePicker from "expo-image-picker";
import { LinearGradient } from "expo-linear-gradient";
import { memberCertificationFnAPi } from "./api";
import { ToastAPI } from "@/components/Toast";
import SelectionModal from "@/components/SelectionModal";
import { useTranslation } from "react-i18next";

export default function FoundationCertification() {
  const { t } = useTranslation();

  const router = useRouter(); // 获取路由对象
  const appState = useAppStateChange();
  const [username, setUsername, handleUsernameDone] = useInputWithDone() as any;
  const [identitycard, setIdentitycard, handleIdentitycardDone] =
    useInputWithDone() as any;

  // 验证手机号或邮箱号格式
  const [identitycardError, setIentitycardError] = useState<string | null>(
    null
  );
  const validateIdentitycard = (input: string) => {
    setIdentitycard(input);
    const idCardRegex = /^(\d{15}$|^\d{17}([0-9]|X|x))$/;
    const reslt = idCardRegex.test(input);
    setIentitycardError(reslt ? null : t("auth.invalid_id_card"));
  };

  const [idFrontImage, setIdFrontImage] = useState<string | null>(null);
  const [idFrontImageBase, setIdFrontImageBase] = useState<any | null>(null);
  const [idReverseImage, setIdReverseImage] = useState<string | null>(null);
  const [idReverseImageBase, setIdReverseImageBase] = useState<any | null>(
    null
  );
  const [networkModalVisible, setNetworkModalVisible] = useState(false);
  const [networkItemInfo, setNetworkItemInfo] = useState<any>({
    name: t("auth.id_card"),
    type: 0,
  });
  const pickImage = async (
    setImage: (uri: string | null) => void,
    setImageBase?: (uri: string | null) => void
  ) => {
    // 检查权限
    let permissionResult =
      await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (permissionResult.granted === false) {
      Alert.alert(
        t("auth.permission_denied"),
        t("auth.allow_access_photos"),
        [{ text: t("auth.confirm") }],
        { cancelable: false }
      );
      return;
    }
    let pickerResult = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
    });
    if (!pickerResult.canceled) {
      setImage(pickerResult.assets[0].uri);
      setImageBase?.(pickerResult.assets[0] as any);
    }
  };

  const handleCertification = async () => {
    if (!username || !identitycard || !idFrontImage || !idReverseImage) {
      ToastAPI.warning(t("auth.input_incomplete"));
      return;
    }
    ToastAPI.loading(t("auth.certifying_uploading"), "center", -1);
    const formData = new FormData();
    formData.append("certificationType", "0");
    formData.append("realName", username);
    formData.append("identityNumber", identitycard);
    // 处理身份证正面
    formData.append("files", idFrontImageBase as any);
    if (networkItemInfo.type === 0) {
      // 处理身份证反面
      formData.append("files", idReverseImageBase as any);
    }
    const puyload = {
      certificationType: networkItemInfo.type,
      realName: username,
      identityNumber: identitycard,
      base64Group:
        networkItemInfo.type === 0
          ? `${idFrontImageBase["base64"]},${idReverseImageBase["base64"]}`
          : `${idFrontImageBase["base64"]}}`,
      fileNames:
        networkItemInfo.type === 0
          ? `${idFrontImageBase["fileName"]},${idReverseImageBase["fileName"]}`
          : `${idFrontImageBase["fileName"]}`,
    };
    try {
      const memberCertificationFnAPiRes: any = await memberCertificationFnAPi(
        puyload
      );
      ToastAPI.close();
      if (memberCertificationFnAPiRes.code === 0) {
        ToastAPI.success(t("auth.certification_success"));
        router.back();
      } else {
        ToastAPI.error(
          memberCertificationFnAPiRes?.errMsg ||
            t("auth.certification_failure")
        );
      }
    } catch (error) {
      ToastAPI.close();
      // 捕获错误并关闭加载提示
      ToastAPI.error(JSON.stringify(error) || t("auth.request_error"));
    }
  };
  return (
    <PageContainer>
      <View className="bg-[#000] flex-1 p-[13px]">
        <View className="items-center flex-row h-[46px]">
          <TouchableOpacity onPress={() => router.back()}>
            <Image
              source={require("@/assets/images/return-left.png")}
              className="w-[18px] h-[18px]"
            />
          </TouchableOpacity>
          <View className="flex-1 flex-row justify-center">
            <Text className="text-[#fff] text-[18px]">
              {t("auth.basic_certification")}
            </Text>
          </View>
          <View className="w-[18px]"></View>
        </View>
        <ScrollView
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          style={{ flex: 1 }}
        >
          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("auth.name")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              returnKeyType="done"
              onSubmitEditing={handleUsernameDone}
              blurOnSubmit={true}
              placeholder={t("auth.please_input_name")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={username}
              onChangeText={setUsername}
            />
          </View>
          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("auth.id_card")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              placeholder={t("auth.please_input_id_card")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={identitycard}
              returnKeyType="done"
              onSubmitEditing={handleIdentitycardDone}
              blurOnSubmit={true}
              onChangeText={validateIdentitycard}
            />
            {identitycardError && (
              <Text style={{ color: "red", fontSize: 12, marginTop: 5 }}>
                {identitycardError}
              </Text>
            )}
          </View>
          <View className="mt-[22px]">
            <Text className="text-[#D7D7D7] text-[16px]">
              {t("auth.id_card_passport")}
            </Text>
            <TouchableOpacity
              onPress={() => {
                setNetworkModalVisible(true);
              }}
            >
              <View
                style={styles.input}
                className="flex-row justify-between px-[12px]"
              >
                <Text
                  className="flex-1 text-[14px] leading-[50px]"
                  style={{ color: !networkItemInfo ? "#949494" : "#fff" }}
                >
                  {!networkItemInfo
                    ? t("auth.select_type")
                    : networkItemInfo.name}
                </Text>
                <Text className="text-[rgb(83,192,255)] text-[14px] leading-[50px]">
                  {t("auth.switch_type")}
                </Text>
              </View>
            </TouchableOpacity>
          </View>
          <View>
            <TouchableOpacity
              onPress={() => pickImage(setIdFrontImage, setIdFrontImageBase)}
            >
              <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
                {networkItemInfo.type === 0
                  ? t("auth.upload_id_front")
                  : t("auth.upload_passport_front")}
              </Text>
              <Image
                source={
                  idFrontImage
                    ? { uri: idFrontImage }
                    : require("@/assets/images/idFront.png")
                }
                className="w-full h-[180px] mt-[22px] rounded-[10px]"
              ></Image>
            </TouchableOpacity>
          </View>
          {networkItemInfo.type === 0 && (
            <View className="pb-[70px]">
              <TouchableOpacity
                onPress={() =>
                  pickImage(setIdReverseImage, setIdReverseImageBase)
                }
              >
                <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
                  {t("auth.upload_id_reverse")}
                </Text>
                <Image
                  source={
                    idReverseImage
                      ? { uri: idReverseImage }
                      : require("@/assets/images/id-reverseside.png")
                  }
                  className="w-full h-[180px] mt-[22px] rounded-[10px]"
                ></Image>
              </TouchableOpacity>
            </View>
          )}
        </ScrollView>
        <View style={styles.buttonContainer}>
          <TouchableOpacity onPress={handleCertification}>
            <LinearGradient
              style={styles.ntn}
              colors={["#3D7FFF", "#6FC2FA"]}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 0 }}
            >
              <Text className="text-[#fff] text-[16px]">
                {" "}
                {t("auth.certify")}
              </Text>
            </LinearGradient>
          </TouchableOpacity>
        </View>
      </View>
      <SelectionModal
        visible={networkModalVisible}
        title={t("auth.auth-type")}
        listData={[
          { name: t("auth.id_card"), type: 0 },
          { name: t("auth.passport"), type: 1 },
        ]}
        renderKey="name"
        onClose={() => setNetworkModalVisible(false)}
        onSelect={async (item: any) => {
          setNetworkItemInfo(item);
          setNetworkModalVisible(false);
        }}
        renderItem={(item) => (
          <View className="flex-1">
            <View className="flex-row justify-between gap-[10px] items-center">
              <Text className="text-[#fff] text-[16px]">{item.name}</Text>
            </View>
          </View>
        )}
      />
    </PageContainer>
  );
}
const styles = StyleSheet.create({
  scrollContainer: {
    flexGrow: 1, // 使内容能够伸展
    justifyContent: "center", // 中心对齐
  },
  input: {
    height: 50,
    backgroundColor: "#25262A",
    borderRadius: 10,
    marginTop: 15,
  },
  ntn: {
    height: 50,
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 22,
  },
  buttonContainer: {
    position: "absolute",
    bottom: 0,
    left: 0,
    right: 0,
    paddingLeft: 13,
    paddingRight: 13,
    paddingBottom: 13,
    backgroundColor: "#000", // 可根据需要调整背景颜色
  },
});
